package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.WeChatConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import com.sky.vo.UserReportVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private JwtProperties jwtProperties;


    /**
     * 用户端微信登录
     *
     * @param userLoginDTO dto
     * @return vo
     */
    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        //1. openid，通过微信官方接口获取
        Map<String, String> param = new HashMap<>();
        param.put("appid", weChatProperties.getAppid());
        param.put("secret", weChatProperties.getSecret());
        param.put("js_code", userLoginDTO.getCode());
        param.put("grant_type", "authorization_code"); //授权类型，固定值

        // 发送请求
        String body = HttpClientUtil.doGet(WeChatConstant.WX_LOGIN, param);
        String openid = (String) JSON.parseObject(body).get("openid");

        //2. 根据openid判断用户是否注册
        User user = userMapper.getByOpenid(openid);
        if (user == null) {
            user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            userMapper.insert(user);
        }

        //3.生成jwt令牌
        Map<String, Object> map = new HashMap<>();
        map.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                map);

        return UserLoginVO.builder()
                .openid(openid)
                .id(user.getId())
                .token(token)
                .build();

    }

    /**
     * 用户人数统计接口
     *
     * @param begin 开始日期
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        // 1 定义三个集合(日期,新增用户数,用户总数)
        List<String> dateList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();

        // 2遍历日期,查询每天的业务数据
        while (!begin.isAfter(end)) {
            LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

            // 查询每日的增长用户
            Map<String, Object> map = new HashMap<>();
            map.put("begin", beginTime);
            map.put("end", endTime);

            Integer newUser = userMapper.countByMap(map);

            // 查询当前日期的总用户数
            map.put("begin", null);
            Integer totalUser = userMapper.countByMap(map);
            dateList.add(begin.toString());
            newUserList.add(newUser);
            totalUserList.add(totalUser);

            begin = begin.plusDays(1);
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
    }

    /**
     * 查询今日新增用户数
     *
     * @return 新增用户数量
     */
    @Override
    public Integer getTodayUsers(LocalDateTime beginTime) {
       return userMapper.getTodayUsers(beginTime);
    }
}
